package edu.ito.wx.push;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.ito.wx.model.Template;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;


public class PushMessage {

    public static String pushMessage(String url, Template template){

        HttpPost httpPost = new HttpPost(url);
        HttpClient client = new DefaultHttpClient();
        String respContent = null;

        String json = JSON.toJSONString(template);
        final JSONObject jsonObject = JSON.parseObject(json);
        try {
            StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            HttpResponse response = client.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity he =  response.getEntity();
                respContent = EntityUtils.toString(he,"UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return respContent;

    }


}
